﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using HySoft.Cash.BaseClass;
using System.Configuration;
using Huayou.Common;
using PayRoller.Code;
using System.Web.SessionState;
using HySoft.Cash.Business;
using HySoft.Cash;
using HySoft.Cash.Structure;
using HiLand.Utility.Data;
using Huayou.Utils;
using System.Net.Mail;
using System.Runtime.Remoting.Messaging;
using System.Text;

namespace PayRoller.Manage.Reports
{
    public partial class StatementReportList : ParentPage, IRequiresSessionState
    {
        private float totalBalanceNeed = 0.0F;
        private float totalBalancePaid = 0.0F;
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.dgdList.DataBind();
        }

        protected void dgdList_DataBinding(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            string commandText = "";
            string whereClause = "";

            //int invoiceStatusSelected = Converter.GetEnumValue<InvoiceStatuses>(this.DDLInvoiceStatus.SelectedValue);
            //if (invoiceStatusSelected != 0)
            //{
            //    whereClause += string.Format(" and  i.IsValid={0}", invoiceStatusSelected);
            //}

            string invoiceStatusSelected = ddlInvoiceStatus.SelectedValue.ToLower();
            if (string.IsNullOrEmpty(invoiceStatusSelected) == false)
            {
                string overDueIDs = GetOverDueOrgIDs();
                switch (invoiceStatusSelected)
                {
                    case "overdue":
                        if (overDueIDs != string.Empty)
                        {
                            whereClause += " and OrgID in  ( " + overDueIDs + " ) ";
                        }
                        break;
                    case "normal":
                        if (overDueIDs != string.Empty)
                        {
                            whereClause += " and OrgID not in  ( " + overDueIDs + " ) ";
                        }
                        break;
                    default:
                        break;
                }
            }

            int orgIDSelected = this.UOrgNameInput.OrgIDSelected;
            if (orgIDSelected > 0)
            {
                whereClause = whereClause + " and Orgid=" + orgIDSelected;
            }
            if (!this.txtFromDate.Text.Trim().Equals("") && (this.txtFromDate.Text.Trim() != "dd/mm/yyyy"))
            {
                whereClause = whereClause + " and StatementDate>='" + this.txtFromDate.Text + "'";
            }
            if (!this.txtToDate.Text.Trim().Equals("") && (this.txtToDate.Text.Trim() != "dd/mm/yyyy"))
            {
                whereClause = whereClause + " and StatementDate<='" + this.txtToDate.Text + "'";
            }
            commandText = "select i.*,o.OrgName,o.PreferredEmail,(TotalPrincipal+ TotalInterest + TotalPenalty+ TotalLateInterestCharges) as TotalBalanceNeed,(TotalPrincipalPaid+ TotalInterestPaid+ TotalPenaltyPaid+ TotalLateInterestChargesPaid) as TotalBalancePaid from tStatementMaster as i left join tOrgInfo as o ON i.OrgID =o.Sid where 1=1  " + whereClause + " order by i.ID desc";

            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["SQLConnString"], CommandType.Text, commandText).Tables[0];
            CommonBasePage.SetPage(this.dgdList, dt);
            base.AddValue("pageno", Convert.ToString((int)(this.dgdList.CurrentPageIndex + 1)));
            this.txtParamstr.Text = base.PackPart(base.ParamValue);
        }


        /// <summary>
        /// 账单ID，账单字典
        /// </summary>
        private Dictionary<int, TStatementDT> StatementDic
        {
            get
            {
                if (this.ViewState["StatementDic"] == null)
                {
                    this.ViewState["StatementDic"] = new Dictionary<int, TStatementDT>();
                }

                return this.ViewState["StatementDic"] as Dictionary<int, TStatementDT>;
            }
            set
            {
                this.ViewState["StatementDic"] = value;
            }
        }

        protected void dgdList_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            this.dgdList.CurrentPageIndex = e.NewPageIndex;
            this.dgdList.DataBind();
        }

        protected override void Render(HtmlTextWriter writer)
        {
            this.litDisplay.Text = string.Format("(Total Balance: {0})", this.totalBalanceNeed.ToString("0.00"));
            base.Render(writer);
        }


        protected override void OnInit(EventArgs e)
        {
            base.m_ModuleCode = "";
            base.CheckLogin(true);
            base.CheckPerm();
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                base.ParamValue = base.UnPack();
                this.txtParamstr.Text = base.PackPart(base.ParamValue);
                string str = base.GetValue("pageno");
                if (str != null)
                {
                    this.dgdList.CurrentPageIndex = Convert.ToInt32(str) - 1;
                }
                this.dgdList.DataBind();
            }
            else
            {
                base.ParamValue = base.UnPackPart(this.txtParamstr.Text);
            }
        }

        protected void dgdList_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            ListItemType itemType = e.Item.ItemType;
            if (itemType == ListItemType.AlternatingItem || itemType == ListItemType.Item || itemType == ListItemType.SelectedItem)
            {
                DataRowView drv = e.Item.DataItem as DataRowView;
                int currentOrgID = Convert.ToInt32(drv["OrgID"]);
                string orgDetailsURl = string.Format("~/manage/OrgInfo/Index.aspx?OrgSid={0}", currentOrgID);
                int statementID = Convert.ToInt32(drv["ID"]);

                if (StatementDic.ContainsKey(statementID) == false)
                {
                    TStatementDT statementDT = TStatementDT.ConvertFrom(drv.Row);
                    StatementDic.Add(statementID, statementDT);
                }

                if ((drv["TotalBalanceNeed"] is DBNull) == false)
                {
                    try
                    {
                        totalBalanceNeed += Convert.ToSingle(drv["TotalBalanceNeed"]);
                    }
                    catch
                    { }
                }

                if ((drv["TotalBalancePaid"] is DBNull) == false)
                {
                    try
                    {
                        totalBalancePaid += Convert.ToSingle(drv["TotalBalancePaid"]);
                    }
                    catch
                    { }
                }

                HyperLink hlOurRefID = e.Item.FindControl("hlOurRefID") as HyperLink;
                if (hlOurRefID != null)
                {
                    hlOurRefID.NavigateUrl = orgDetailsURl;
                    hlOurRefID.Text = currentOrgID.ToString();
                }

                HyperLink hlClientName = e.Item.FindControl("hlClientName") as HyperLink;
                if (hlClientName != null)
                {
                    hlClientName.NavigateUrl = orgDetailsURl;
                    hlClientName.Text = drv["OrgName"].ToString();
                }

                Label hlBalanceNeed = e.Item.FindControl("hlBalanceNeed") as Label;
                if (hlBalanceNeed != null)
                {
                    hlBalanceNeed.Text = drv["TotalBalanceNeed"].ToString();
                }

                Label hlBalancePaid = e.Item.FindControl("hlBalancePaid") as Label;
                if (hlBalancePaid != null)
                {
                    hlBalancePaid.Text = drv["TotalBalancePaid"].ToString();
                }

                Label hlStatus = e.Item.FindControl("hlStatus") as Label;
                if (hlStatus != null)
                {
                    //目前状态来显示 当前用户是否有逾期的账单
                    bool isOverDued = false;
                    for (int i = 0; i < OverDuedInvoiceList.Count; i++)
                    {
                        if (OverDuedInvoiceList[i].OrgSid == currentOrgID)
                        {
                            isOverDued = true;
                            break;
                        }
                    }

                    if (isOverDued == true)
                    {
                        hlStatus.Text = "OverDue";
                    }
                    else
                    {
                        hlStatus.Text = "Normal";
                    }

                    //StatementStatuses status = (StatementStatuses)Convert.ToInt32(drv["Status"]);
                    //hlStatus.Text = TStatementBN.GetStatementStatusText(status);
                }

                Label hlDateOfStatement = e.Item.FindControl("hlDateOfStatement") as Label;
                if (hlDateOfStatement != null)
                {
                    hlDateOfStatement.Text = Convert.ToDateTime(drv["StatementDate"]).ToString(AppSettings.DateFormatAU, AppSettings.CurrentCulture);
                }

                string invoiceDetailsUrl = string.Format("~/Manage/Reports/StatementDetails.aspx?Guid={0}&OrgSid={1}", drv["Guid"].ToString(), currentOrgID);
                HyperLink hlDetails = e.Item.FindControl("hlDetails") as HyperLink;
                if (hlDetails != null)
                {
                    hlDetails.NavigateUrl = invoiceDetailsUrl;
                    hlDetails.Text = "Details";
                }

                HyperLink hlStatementNo = e.Item.FindControl("hlStatementNo") as HyperLink;
                if (hlStatementNo != null)
                {
                    hlStatementNo.NavigateUrl = invoiceDetailsUrl;
                    hlStatementNo.Text = statementID.ToString();
                }

                LinkButton libSendStatus = e.Item.FindControl("libSendStatus") as LinkButton;
                if (libSendStatus != null)
                {
                    libSendStatus.CommandArgument = statementID.ToString();
                    StatementSendStatuses sendStatus = (StatementSendStatuses)Convert.ToInt32(drv["SendStatus"]);
                    if (sendStatus == StatementSendStatuses.NeedSend || sendStatus == StatementSendStatuses.NeedReSend)
                    {
                        libSendStatus.Text = "Send";
                    }
                    else
                    {
                        libSendStatus.Text = "ReSend";
                    }
                }
            }
        }

        private string GetOverDueOrgIDs()
        {
            string result = string.Empty;
            if (OverDueOrgIDList != null)
            {
                foreach (int currentOrgID in OverDueOrgIDList)
                {
                    result += currentOrgID + ",";
                }
            }

            if (result.EndsWith(","))
            {
                result = result.TrimEnd(',');
            }

            return result;
        }

        private List<int> overDueOrgIDList;
        private List<int> OverDueOrgIDList
        {
            get
            {
                if (overDueOrgIDList == null && OverDuedInvoiceList != null)
                {
                    overDueOrgIDList = new List<int>();
                    foreach (TinvoicelistDT invoiceEntity in OverDuedInvoiceList)
                    {
                        if (overDueOrgIDList.Contains(invoiceEntity.OrgSid) == false)
                        {
                            overDueOrgIDList.Add(invoiceEntity.OrgSid);
                        }
                    }
                }

                return overDueOrgIDList;
            }
        }




        private List<TinvoicelistDT> overDuedInvoiceList;
        private List<TinvoicelistDT> OverDuedInvoiceList
        {
            get
            {
                if (overDuedInvoiceList == null)
                {
                    overDuedInvoiceList = TinvoicelistBN.GetOverDueInvoiceList();
                }
                return overDuedInvoiceList;
            }
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            string[] statementIDsSelected = DataGridUtils.getID(this.dgdList);
            for (int i = 0; i < statementIDsSelected.Length; i++)
            {
                int currentStatementID = Convert.ToInt32(statementIDsSelected[i]);
                SendMail(currentStatementID);
            }
        }

        private void SendMail(int statementID)
        {
            try
            {
                int pathPos = this.Request.Url.OriginalString.IndexOf(this.Request.Url.PathAndQuery);
                string domainString = this.Request.Url.OriginalString.Substring(0, pathPos);


                string invoiceGUID = StatementDic[statementID].Guid.ToString();
                string receiverMail = StatementDic[statementID].PreferredEmail;
                string orgName = StatementDic[statementID].OrgName;
                DateTime StatementDate = StatementDic[statementID].StatementDate;

                string statementDetailsUrl = string.Format("{1}/Manage/Reports/StatementDetails.aspx?Guid={0}", invoiceGUID, domainString);
                string outputDir = HttpContext.Current.Server.MapPath("~/PDF/Statement");

                string subject = "New Invoice from Golden Bridge";
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("Dear [{0}],", orgName);
                sb.AppendLine();
                sb.AppendLine();
                sb.AppendFormat("Please kindly find the attached Account Statement as of [{0}].", StatementDate.ToString(AppSettings.DateFormatAU));
                sb.AppendLine();
                sb.AppendLine();
                sb.AppendFormat("For further information please log onto your Payroller account by clicking on <a href=\"http://payroller.com.au/Login.aspx\">http://payroller.com.au/Login.aspx</a> or contact us at 1300 137 906.");
                sb.AppendLine();
                sb.AppendLine();
                sb.AppendLine("Best regards,");
                sb.AppendLine();
                sb.AppendLine("Customer Support Team");
                sb.AppendLine("Golden Bridge Payroller™");
                sb.AppendLine();
                sb.AppendLine("☎ 1300 137 906");
                sb.AppendLine("<FONT style=\"FONT-SIZE: 10pt; COLOR: #000; FONT-FAMILY: Webdings\">&Ecirc;</FONT> 1300 138 916 ");
                sb.AppendLine("✉ <A href=\"mailto:support@payroller.com.au\">support@payroller.com.au</a>");
                sb.AppendLine("<FONT style=\"FONT-SIZE: 10pt; COLOR: #000; FONT-FAMILY: Webdings\">ü</FONT><a href=\"http://www.payroller.com.au\"> www.payroller.com.au</a>");
                string body = sb.ToString();
                PDFAndMail.CreatePDFAndSendMail(statementDetailsUrl, outputDir, receiverMail, subject, body);
            }
            catch
            { }
        }

        protected void dgdList_ItemCreated(object sender, DataGridItemEventArgs e)
        {
            ListItemType listItemType = e.Item.ItemType;
            if (listItemType == ListItemType.Item || listItemType == ListItemType.AlternatingItem)
            {
                LinkButton libSendStatus = e.Item.FindControl("libSendStatus") as LinkButton;
                if (libSendStatus != null)
                {
                    libSendStatus.Click += new EventHandler(libSendStatus_Click);
                }
            }
        }

        void libSendStatus_Click(object sender, EventArgs e)
        {
            int statementID = 0;
            LinkButton t = sender as LinkButton;
            if (t != null)
            {
                int.TryParse(t.CommandArgument, out statementID);
            }

            if (statementID > 0)
            {
                SendMail(statementID);

                String connString = AppSettings.ConnectionString;
                string commString = string.Format("UPDATE [tStatementMaster]   SET [SendStatus] = {0} WHERE [ID]={1}", (int)StatementSendStatuses.Sent, statementID);
                SqlHelper.ExecuteNonQuery(connString, CommandType.Text, commString);

                this.dgdList.DataBind();
            }
        }
    }
}